Page({
  data: {
    idcardFrontUrl: '/static/images/avatar_1.jpg',
    idcardBackUrl: '/static/images/avatar_2.jpg',
    name: '',
    gender: 0,
    mobile: '',
    id: ''
  },
  onLoad ({ point, building, room, id }) {
    if (id) {
      this.setData({ id })
      this.getDetail()
      wx.setNavigationBarTitle({ title: '编辑房屋信息' })
    } else {
      this.setData({ point, building, room })
    }
  },
  async getDetail () {
    const res = await wx.$http.get(`/room/${this.data.id}`)
    if (res.code !== 10000) return wx.$utils.toast('获取详情失败')
    this.setData({
      ...res.data
    })
  },
  goList () {
    // 关闭所有页面，打开到应用内的某个页面
    wx.reLaunch({
      url: '/house_pkg/pages/list/index'
    })
  },
  removePicture (ev) {
    // 移除图片的类型（身份证正面或反面）
    const type = ev.mark?.type
    this.setData({ [type]: '' })
  },
  // 选择图片
  async chooseImage (e) {
    console.log(e.mark.dataType)
    const res = await wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sizeType: ['compressed']
    })
    console.log(res.tempFiles[0].tempFilePath)
    wx.uploadFile({
      url: `${wx.$http.baseURL}/upload`,
      filePath: res.tempFiles[0].tempFilePath,
      header: {
        Authorization: getApp().token
      },
      name: 'file',
      success: res => {
        const { data } = JSON.parse(res.data)
        console.log(data.url)
        this.setData({
          [e.mark.dataType]: data.url
        })
      }
    })
  },
  // 验证姓名
  verifyName () {
    const reg = /^[\u4e00-\u9fa5]{2,5}$/
    const valid = reg.test(this.data.name)
    if (!valid) wx.$utils.toast('请输入姓名')
    return valid
  },
  // 验证手机号
  verifyMobile () {
    const reg = /^[1][3-8][0-9]{9}$/
    const valid = reg.test(this.data.mobile)
    if (!valid) wx.$utils.toast('请输入合法手机号')
    return valid
  },
  // 验证图片
  verifyImage () {
    if (this.data.idcardFrontUrl && this.data.idcardBackUrl) return true
    wx.$utils.toast('请上传身份证照片')
    return false
  },
  async submit () {
    // 校验
    if (!this.verifyName()) return
    if (!this.verifyMobile()) return
    if (!this.verifyImage()) return
    // 删除不要的数据
    if (!this.data.id) {
      delete this.data.id
    }
    delete this.data.__webviewId__
    delete this.data.status
    // 上传
    const res = await wx.$http.post('/room', this.data)
    if (res.code !== 10000) return wx.$utils.toast('添加房屋失败')
    wx.$utils.toast('添加房屋成功')
    // 跳转回房屋页面
    this.goList()
  }
})
